﻿using System;
using Abp.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.Helpers;
using System.Web;

namespace Batman.Jianbei.Forum.Controllers.Weixins
{
    public class WeixinAuthController : AbpController
    {
        /// <summary>
        /// 跳转到静默授权页面
        /// </summary>
        /// <param name="url">静默授权回调地址</param>
        /// <returns></returns>
        [Obsolete("使用Index")]
        public ActionResult Silent(string url)
        {
            var appId = Config.WeixinSetting.weixin_app_id;
            var timestamp = JSSDKHelper.GetTimestamp();
            var nonceStr = JSSDKHelper.GetNoncestr();
            string ticket = JsApiTicketContainer.TryGetJsApiTicket(appId, Config.WeixinSetting.weixin_secret);

            var signature = JSSDKHelper.GetSignature(ticket, nonceStr, timestamp, url);

            var state = "my-state"; // 用于验证
            var authorizeUrl = OAuthApi.GetAuthorizeUrl(appId, url, state, OAuthScope.snsapi_base);

            return Redirect(authorizeUrl);
        }

        /// <summary>
        /// 跳转微信授权页面
        /// </summary>
        /// <param name="callback_url">授权成功回调地址</param>
        /// <param name="silence">是否采用静默授权，如果静默授权则获取不到用户名等信息</param>
        /// <returns></returns>
        public IActionResult Index(string callback_url, bool silence = false)
        {
            var appId = Config.WeixinSetting.weixin_app_id;

            var state = "my-state"; // 用于验证
            var oAuthScope = silence ? OAuthScope.snsapi_base : OAuthScope.snsapi_userinfo;
            var authorizeUrl = OAuthApi.GetAuthorizeUrl(appId, callback_url, state, oAuthScope);

            return Redirect(authorizeUrl);
        }
    }
}
